<style>
.el-table tbody tr:hover > td {
  background-color: aliceblue;
  color: #84cff8;
}

.el-table .el-input__inner {
  border: 0;
  text-align: center;
}
</style>
<template>
  <el-card>
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="basic">
        <basic-info-form ref="basicInfo" :info="info"/>
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="cloum">
        <el-table border ref="dragTable"
                  :header-cell-style="{'text-align':'center'}"
                  :cell-style="{'text-align':'center'}"
                  :default-sort="{prop: 'date', order: 'descending'}"
                  :data="columns" row-key="columnId" :max-height="tableHeight"
                  :row-class-name="rowClassName"
                  @row-click="selectThisRow"
                  @selection-change="handleDetailSelectionChange">
          <el-table-column type="selection" min-width="3%" align="center"/>
          <el-table-column label="序号" min-width="4%" prop="sort" sortable>
            <template slot-scope="scope">
              <el-input v-model="scope.row.sort" style="width: 50px">{{ scope.row.sort }}</el-input>
            </template>
          </el-table-column>
          <el-table-column label="金碟字段列名" prop="kdColumnName" min-width="10%">
            <template slot-scope="scope">
              <el-input v-model="scope.row.kdColumnName"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="字段列名" min-width="10%">
            <template slot-scope="scope">
              <el-input v-model="scope.row.columnName"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="字段描述" min-width="10%">
            <template slot-scope="scope">
              <el-input v-model="scope.row.columnComment"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="物理类型" prop="columnType" min-width="10%">
            <template slot-scope="scope">
              <el-input v-model="scope.row.columnType"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="数据类型" min-width="11%">
            <template slot-scope="scope">
              <el-select v-model="scope.row.dataType">
                <el-option label="Long" value="Long"/>
                <el-option label="String" value="String"/>
                <el-option label="Integer" value="Integer"/>
                <el-option label="Double" value="Double"/>
                <el-option label="BigDecimal" value="BigDecimal"/>
                <el-option label="Date" value="Date"/>
                <el-option label="REF" value="REF"/>
                <el-option label="ENVM" value="ENVM"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否主键" min-width="3%">
            <template slot-scope="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isPk"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="是否必填" min-width="3%">
            <template slot-scope="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isRequired"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="是否自增" min-width="3%">
            <template slot-scope="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isAuto" ></el-checkbox>
            </template>
          </el-table-column>
          <!-- &lt;!&ndash;
           </el-table-column>&ndash;&gt;
           <el-table-column label="过滤方式" min-width="10%">
             <template slot-scope="scope">
               <el-select v-model="scope.row.filterType">
                 <el-option label="=" value="EQ" />
                 <el-option label="!=" value="NE" />
                 <el-option label=">" value="GT" />
                 <el-option label=">=" value="GTE" />
                 <el-option label="<" value="LT" />
                 <el-option label="<=" value="LTE" />
                 <el-option label="LIKE" value="LIKE" />
                 <el-option label="BETWEEN" value="BETWEEN" />
               </el-select>
             </template>
           </el-table-column>-->
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="脚本信息" name="relation">
        <relation-info-form ref="relationInfo" :info="info" :menus="menus"/>
      </el-tab-pane>
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="handleAddDetails"
      >添加
      </el-button>
      <el-button
        type="success"
        icon="el-icon-delete"
        size="mini"
        @click="handleDeleteDetails"
      >删除
      </el-button>
    </el-tabs>
    <el-form>
      <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import {getBusTable, updateBusTable, removeChecked} from "@/api/datafactory/table";
import {optionselect as getDictOptionselect} from "@/api/system/dict/type";
import {listMenu as getMenuTreeselect} from "@/api/system/menu";
import basicInfoForm from "./basicInfoForm";
import relationInfoForm from "./relationInfoForm";
import Sortable from 'sortablejs'

export default {
  name: "GenEdit",
  components: {
    basicInfoForm,
    relationInfoForm
  },
  data() {
    return {
      // 选中选项卡的 name
      activeName: "cloum",
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 表列信息
      columns: [],
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      //选中的从表数据
      checkedDetail: [],
      //删除数据的ID
      id: [],
      // 表详细信息
      info: {},
    };
  },
  created() {
    const tableId = this.$route.params && this.$route.params.tableId;
    if (tableId) {
      // 获取表详细信息
      getBusTable(tableId).then(res => {
        this.columns = res.data.rows;
        this.info = res.data.info;
      });
      /** 查询字典下拉列表 */
      /*getDictOptionselect().then(response => {
        this.dictOptions = response.data;
      });*/
      /** 查询菜单下拉列表 */
      /*getMenuTreeselect().then(response => {
        this.menus = this.handleTree(response.data, "menuId");
      });*/
    }
  },
  methods: {
    handleDeleteDetails() {
      if (this.checkedDetail.length == 0) {
        this.$alert("请先选择要删除的数据", "提示", {
          confirmButtonText: "确定",
        });
      } else {
        if(this.id[0] != null){
          removeChecked(parseInt(this.id)).then(res => {
            if (res.code === 200) {
              this.msgSuccess("删除成功");
              this.columns.splice(this.checkedDetail[0].xh - 1, 1)
            }
          });
        } else {
          this.columns.splice(this.checkedDetail[0].xh - 1, 1)
        }

      }
    },
    //添加一行数据
    handleAddDetails() {
      if (this.columns == undefined) {
        this.columns = new Array();
      }
      let obj = {};
      obj.tableName = this.info.busTableName;
      obj.kdColumnName = "";
      obj.columnName = "";
      obj.columnComment = "";
      obj.columnType = "varchar(60)";
      obj.dataType = "String";
      obj.dataModel = "";
      obj.sort = (this.columns.length + 1)
      obj.isList = "1"
      this.columns.push(obj);
    },
    rowClassName({row, rowIndex}) {
      row.xh = rowIndex + 1;
    },
    //单选框选中数据
    handleDetailSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.dragTable.clearSelection();
        this.$refs.dragTable.toggleRowSelection(selection.pop());
      } else {
        this.id = selection.map(item => item.columnId)
        this.checkedDetail = selection;
      }
    },
    //单选框左键选中
    selectThisRow(row) {
      this.$refs.dragTable.toggleRowSelection(row);
    },
    /** 提交按钮 */
    submitForm() {
      const basicForm = this.$refs.basicInfo.$refs.basicInfoForm;
      const relationForm = this.$refs.relationInfo.$refs.relationInfoForm;
      Promise.all([basicForm, relationForm].map(this.getFormPromise)).then(res => {
        const validateResult = res.every(item => !!item);
        if (validateResult) {
          const busTable = Object.assign({}, basicForm.model, relationForm.model);
          busTable.columns = this.columns;
          /*genTable.params = {
            treeCode: genTable.treeCode,
            treeName: genTable.treeName,
            treeParentCode: genTable.treeParentCode,
            parentMenuId: genTable.parentMenuId
          };*/
          console.log(busTable);
          if (busTable.busTableName==null){
            this.msgError("字段列名不能为空，请重新检查提交内容");
          }else {
            updateBusTable(busTable).then(res => {
              this.msgSuccess(res.msg);
              if (res.code === 200) {
                this.close();
              }
            });
          }
        } else {
          this.msgError("表单校验未通过，请重新检查提交内容");
        }
      });
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },
    /** 关闭按钮 */
    close() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({path: "/bus/table/index", query: {t: Date.now()}})
    }
  },
  mounted() {
    const el = this.$refs.dragTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
    const sortable = Sortable.create(el, {
      handle: ".allowDrag",
      onEnd: evt => {
        const targetRow = this.columns.splice(evt.oldIndex, 1)[0];
        this.columns.splice(evt.newIndex, 0, targetRow);
        for (let index in this.columns) {
          this.columns[index].sort = parseInt(index) + 1;
        }
      }
    });
  }

};
</script>
